﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.IO.Compression;
using Ionic.Zip;

namespace ArchiveIISLogs
{
    public class Compressor
    {
        public void AddLogFileToZip(string zipFileName, FileInfo logFile)
        {
            using (ZipFile zip = new ZipFile(zipFileName))
            {
                RemoveFileInZipIfAlreadyExists(zip, logFile.Name);
                zip.AddFile(logFile.FullName, "");
                zip.Save();
            }
        }

        private void RemoveFileInZipIfAlreadyExists(ZipFile zip, string logFileName)
        {
            if (zip[logFileName] != null)
            {
                zip[logFileName] = null;
            }
        }

        public void CompressIt(string originalFileName, string compressToFileName)
        {
            // Bytes array in which we're going to store the actual file to be compressed
            byte[] bufferWrite;

            using (FileStream fsSource = new FileStream(originalFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                bufferWrite = new byte[fsSource.Length];// Set the buffer size to the size of the file
                fsSource.Read(bufferWrite, 0, bufferWrite.Length);// Read the data from the stream into the buffer            
                FileStream fsDest = new FileStream(compressToFileName, FileMode.OpenOrCreate, FileAccess.Write);
                GZipStream gzCompressed = new GZipStream(fsDest, CompressionMode.Compress, true);// Will hold the compressed stream created from the destination stream
                gzCompressed.Write(bufferWrite, 0, bufferWrite.Length);            // Write the compressed stream from the bytes array to a file

                fsSource.Close();
                gzCompressed.Close();
                fsDest.Close();
            }
        }

        public void RemoveLogsInZipOlderThan(string zipFileName, DateTime thresholdDate)
        {
            using (ZipFile zip = new ZipFile(zipFileName))
            {
                //find those that need to be removed.
                List<ZipEntry> filesInZipToDelete = new List<ZipEntry>();

                if (zip.Entries != null)
                {
                    foreach (ZipEntry e in zip)
                    {
                        if (e.LastModified < thresholdDate)
                        {
                            filesInZipToDelete.Add(e);
                        }
                    }

                    foreach (ZipEntry e in filesInZipToDelete)
                    {
                        zip.RemoveEntry(e);
                    }
                    zip.Save();
                }
            }
        }
    }
}
